package testcase;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.ArrayList;

import junit.framework.TestCase;
import impl.UniversityImpl;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import dataobj.CourseTO;
import MainComponent.CourseOperate;

public class TestCourseOperate extends TestCase{
	
	private CourseOperate co;
	private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
	
	class testImpl extends UniversityImpl{

		@Override
		public ArrayList<CourseTO> getCourses(File file) {
			return null;
		}
		
	}
	
	@Before
	public void setUp(){
		System.setOut(new PrintStream(outContent));
	}
	
	@After
	public void cleanUp() throws Exception{
		outContent.reset();
		System.setOut(null);
	}

	
	public UniversityImpl getImpl(CourseOperate obj) throws Exception{
		UniversityImpl fieldValue = null;
		Field implField = CourseOperate.class.getDeclaredField("impl");
		implField.setAccessible(true);
		fieldValue = (UniversityImpl) implField.get(obj);
		return fieldValue;
	}

	public void setImpl(CourseOperate obj, UniversityImpl impl) throws Exception{
		Field implField = CourseOperate.class.getDeclaredField("impl");
		implField.setAccessible(true);
		implField.set(obj, impl);
	}
	
	//Test constructor with correct university
	@Test
	public void testCourseOperate1() throws Exception{
		co = new CourseOperate("cityu");
		assertEquals(getImpl(co) instanceof impl.UniversityImpl, true);
	}
	
	//Test constructor with incorrect university
	@Test
	public void testCourseOperate2() throws Exception{
		co = new CourseOperate("test");
		assertEquals(getImpl(co) == null, true);
		assertEquals("FATAL ERROR: Not such university\n", outContent.toString());
	}
	
	//Test getCourses method
	//Assume the impl is wrong
	@Test
	public void testGetCoursesMethod1(){
		co = new CourseOperate("test");
		File file = new File("");
		assertEquals(co.getCourses(file).size(), 0);
		assertEquals("FATAL ERROR: Not such university\n", outContent.toString());
	}
	
	//Assume the impl is correct
	@Test
	public void testGetCoursesMethod2() throws Exception{	
		co = new CourseOperate("cityu");
		setImpl(co, new testImpl());
		File file = new File("");
		assertEquals(co.getCourses(file), null);
	}

}
